"use client";
import {
    getCommissionApi,
    getRegisterCountApi,
    getTotalCountApi,
    getWithdrawalApi,
} from "@/api/summary";
import { CommissionModel } from "@/app/[locale]/affiliate/component/TabsCom";
import Table, { TableHeaderItem } from "@/components/Table";
import TipsModal, { ModalProps } from "@/components/TipsModal";
import { usePathname } from "@/i18n/routing";
import { useUserInfoStore } from "@/stores/useUserInfoStore";
import { server } from "@/utils/client";
import { getToken } from "@/utils/Cookies";
import { copyText, flatPoint } from "@/utils/methods";
import { useRequest } from "ahooks";
import { Mask, Toast } from "antd-mobile";
import { useTranslations } from "next-intl";
import Image from "next/image";
import { FC, useEffect, useRef, useState } from "react";
import "./page.scss";

interface Props {}

const RulesClient = () => {
    const t = useTranslations("cashback");
    const [rules, setRules] = useState<any>([]);
    const [visible, setVisible] = useState(false);
    const columns: TableHeaderItem[] = [
        {
            title: <div className={"text-center text-[#98a7b5]"}>Nivel Agente</div>,
            dataIndex: "agent_level",
            align: "center",
            render: (item: any) => (
                <div className={"text-[0.12rem] text-[#98a7b5]"}>{item?.agent_level}</div>
            ),
        },
        {
            title: <div className={"text-center text-[#98a7b5]"}>Apostas Validas</div>,
            dataIndex: "bet",
            align: "center",
            render: (item: any) => (
                <div className={"text-[0.12rem] text-[#98a7b5]"}>{item?.bet / 10000} Dez mil+</div>
            ),
        },
        {
            title: <div className={"text-center text-[#98a7b5]"}>Comissão</div>,
            dataIndex: "ratio",
            render: (item: any) => (
                <div className={"text-center text-[0.12rem] text-[#db922b]"}>
                    {flatPoint(item?.ratio / 100)}
                    <span className={"text-[#98a7b5]"}>%</span>
                </div>
            ),
        },
    ];
    const loadMore = async () => {
        return Promise.resolve();
    };

    const getCashBackApi = async () => {
        return server
            .request<any>({
                url: "/v1/api/user/get_user_config_agent_info",
                method: "post",
            })
            .then((res) => {
                return {
                    rules: res.data || [],
                };
            })
            .catch((error) => {
                return {
                    rules: [],
                    last_period: { end_time: 0, start_time: 0 },
                    next_period: {
                        end_time: 0,
                        start_time: 0,
                    },
                    amount: 0,
                    bet: 0,
                    status: "expired",
                };
            });
    };
    useEffect(() => {
        getCashBackApi().then((res) => {
            setRules(res.rules);
        });
    }, []);
    return (
        <div className={"text-[0.12rem]"}>
            <div className={"bg-[#0e1319] p-[0.0694rem]"}>
                <Table
                    columns={columns}
                    headerClassName={" bg-[#151d28]  "}
                    bodyClassName={"odd:bg-[#0e1319] even:bg-[#151d28]"}
                    dataSource={rules || []}
                    loadMore={loadMore}
                    hasMore={false}
                    isLoadMore={false}
                    isBackground={false}
                />
            </div>
            <div className={"mt-[0.1389rem] flex items-center text-[#98a7b5]"}>
                <p
                    className={"mr-[0.1389rem] h-[0.0694rem] w-[0.0694rem] rounded bg-[#98a7b5]"}
                ></p>{" "}
                A apostas válidas depende dos diferentes jogos:
            </div>

            <div className={"mt-[0.1389rem] flex bg-[#25262b] p-[0.1389rem] text-[#98a7b5]"}>
                <span className={"iconfont icon-tishi text-[0.10rem]"}></span>
                <div className={"ml-[0.0694rem]"}>
                    Os tipos de crash e os jogos virtuais não serão considerados apostas válidas{" "}
                </div>
            </div>

            <div className={"mt-[0.1389rem] bg-[#25262b] p-[0.1389rem] text-[#98a7b5]"}>
                <div>
                    <span className={"text-[0.22rem] text-[#fff]"}>100%</span>
                    <span> De aposta </span>
                </div>
                <div>
                    <span className={"text-[#575f6a]"}>Jogos : </span>
                    <span> Live Casino, 3rd Party</span>
                </div>
            </div>
            <div className={"mt-[0.1389rem] bg-[#25262b] p-[20px] text-[#98a7b5]"}>
                <div>
                    <span className={"text-[0.22rem] text-[#fff]"}>100%</span>
                    <span> De aposta </span>
                </div>
                <div>
                    <span className={"text-[#575f6a]"}>Jogos : </span>
                    <span>Os outros jogos originais</span>
                </div>
            </div>

            <div
                onClick={() => setVisible(true)}
                className={
                    "mt-[0.1389rem] flex justify-between bg-[#25262b] p-[0.1042rem] text-[#98a7b5]"
                }
            >
                Regras de cálculo de comissão
                <span className={"iconfont icon-xiangyou2"}></span>
            </div>

            <ul className={"ml-[0.1389rem] mt-[0.1389rem] list-disc text-[#98a7b5]"}>
                <li className={"mt-[0.0694rem]"}>
                    As comissões podem ser retiradas em nossa carteira bcwin do painel a qualquer
                    momento.
                </li>
                <li className={"mt-[0.0694rem]"}>O sistema calcula a comissão a cada 3 minutos.</li>
                <li className={"mt-[0.0694rem]"}>Comissão máxima diária : 10000 BRL</li>
                <li className={"mt-[0.0694rem]"}>
                    A comissão não será creditada para o mesmo IP ou dispositivo, e a inflação
                    intencional do volume de negócios não será creditada para a comissão.{" "}
                </li>
            </ul>
            <CommissionModel visible={visible} setVisible={setVisible} />
        </div>
    );
};
const App: FC<Props> = (props) => {
    const t = useTranslations("SummaryPage");

    const sliderRef = useRef<HTMLDivElement>(null);
    const pathname = usePathname();
    const [num, setNum] = useState(100);
    const [money, setMoney] = useState("5000");

    const [visible, setVisible] = useState(false);

    const [BASE_URL, setBaseUrl] = useState("");

    const todayModalRef = useRef<ModalProps>(null);
    const totalModalRef = useRef<ModalProps>(null);
    const { userInfo } = useUserInfoStore();
    const token = getToken();

    // 生成分享链接
    // const BASE_URL = window.location.href.replace(pathname, "");

    const shareUrl = `${BASE_URL}/${userInfo ? userInfo.referrer_code : "xxxxxx"}`;

    const url = encodeURIComponent(`${shareUrl}`);

    const SHARE_SOURCE = [
        {
            icon: "/summary/Facebook.png",
            label: "Facebook",
            shareUrl: `https://www.facebook.com/sharer/sharer.php?u=${url}`,
        },
        {
            icon: "/summary/WhatsApp.png",
            label: "WhatsApp",
            shareUrl: `https://api.whatsapp.com/send?text=${url}`,
        },
        {
            icon: "/summary/Telegram.png",
            label: "Telegram",
            shareUrl: `https://t.me/share/url?url=${url}`,
        },
        {
            icon: "/summary/Twitter.png",
            label: "Twitter",
            shareUrl: `https://twitter.com/intent/tweet?text=${url}`,
        },
        {
            icon: "/summary/Email.png",
            label: "Email",
            shareUrl: `mailto: ?&subject=&cc=&bcc=&body=${url}`,
        },
    ];

    // 轮询时间
    const TIME = 180000;
    const getUserMoneyHandler = () => {
        if (token) {
            return getRegisterCountApi().then((res) => {
                if (res.code === 200) return res.data;
            });
        }
        return Promise.resolve({
            commissar: 0,
            effective_amount: 0,
            recharge_user_count: 0,
            reg_count: 0,
        });
    };

    const { data: todayData } = useRequest(getUserMoneyHandler, {
        pollingInterval: TIME,
        pollingWhenHidden: true,
        pollingErrorRetryCount: 3,
        staleTime: 5000,
        refreshDeps: [token],
    });

    const getTotalCount = () => {
        if (token) {
            return getTotalCountApi().then((res) => {
                if (res.code === 200) return res.data;
            });
        }
        return Promise.resolve({
            commissar: 0,
            effective_amount: 0,
            recharge_user_count: 0,
            reg_count: 0,
        });
    };

    const { data: totalData } = useRequest(getTotalCount, {
        pollingInterval: TIME,
        pollingWhenHidden: true,
        pollingErrorRetryCount: 3,
        staleTime: 5000,
    });

    const getCommission = () => {
        if (token) {
            return getCommissionApi().then((res) => {
                if (res.code === 200) return res.data;
            });
        }
        return Promise.resolve({
            commissar: 0,
            level: 0,
            withdrawal_commissions: 0,
            enable_receive: false,
            min_value: 0,
            max_value: 0,
        });
    };

    const { data: commissionData, run: commissionRun } = useRequest(getCommission, {
        pollingInterval: TIME,
        pollingWhenHidden: true,
        pollingErrorRetryCount: 3,
        staleTime: 5000,
    });

    const handleSlide: any = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
        if (sliderRef.current) {
            const startX = sliderRef.current.getBoundingClientRect().x;
            const x = e.clientX - startX;
            const xRem = x / (144 * 0.6);
            const intNum = Math.round(10000 * xRem) - Math.round((10000 * xRem) % 10);
            setNum(intNum);
            const m = intNum * 50;
            let r = "";
            const arr = m.toString().split("");
            arr.forEach((item, i) => {
                if (i !== arr.length - 1 && (arr.length - i - 1) % 3 === 0) {
                    r += item + ",";
                } else {
                    r += item;
                }
            });

            setMoney(r);
            const scale = (Math.round(xRem * 10000) / 100.0).toFixed(2) + "%";
            sliderRef.current.style.width = scale;
        }
    };

    const copy = (text: string) => {
        copyText(text);
        Toast.show({ icon: "success", content: t("copySuc"), maskClickable: false });
    };

    const withdrawalHandler = async () => {
        if (commissionData === undefined) return;
        if (!commissionData.enable_receive) {
            Toast.show(t("receive"));
            return;
        }

        const commissar = commissionData.commissar ?? 0; // 使用空值合并运算符处理可能的 undefined
        const minValue = Math.min(commissionData.min_value, 10);

        if (commissar > minValue) {
            const available = Math.min(commissionData.max_value, commissar);
            getWithdrawalApi({ amount: available }).then((res) => {
                if (res.code === 200) {
                    setTimeout(commissionRun, 200);
                }
            });
            return;
        } else {
            Toast.show(t("receive"));
        }
    };

    useEffect(() => {
        setBaseUrl(window.location.href.replace(pathname, ""));
    }, []);
    return (
        <div className="content">
            <div className="summary referral-router-view">
                <div className="content" style={{ marginTop: 0 }}>
                    <div className="title">
                        <div>
                            {t("Hoje")}
                            <span
                                className="iconfont icon-bangzhu"
                                onClick={() => todayModalRef.current?.onOpen()}
                            />
                        </div>
                    </div>
                    <div className="cardMian">
                        <ul className="statistics-card">
                            <li>
                                <p className="num">{flatPoint(todayData?.reg_count ?? 0)}</p>
                                <p> {t("Inscrições")} </p>
                            </li>
                            <li>
                                <p className="num">
                                    {flatPoint(todayData?.recharge_user_count ?? 0)}
                                </p>
                                <p> {t("Novos")} </p>
                            </li>
                            <li>
                                <p className="num">
                                    <span className={"mr-[5px]"}>{t("R$")}</span>
                                    {flatPoint(todayData?.effective_amount ?? 0)}
                                </p>
                                <p> {t("Aposta")} </p>
                            </li>
                            <li>
                                <p className="num">
                                    <span className={"mr-[5px]"}>{t("R$")}</span>
                                    {flatPoint(todayData?.commissar ?? 0)}
                                </p>
                                <p> {t("Comissão")} </p>
                            </li>
                        </ul>
                    </div>
                </div>
                <div className="content">
                    <div className="title">
                        <div>
                            {t("Total")}
                            <span
                                className="iconfont icon-bangzhu"
                                onClick={() => totalModalRef.current?.onOpen()}
                            />
                        </div>
                    </div>
                    <div className="cardMian">
                        <ul className="statistics-card">
                            <li>
                                <p className="num">{flatPoint(totalData?.reg_count ?? 0)}</p>
                                <p> {t("Inscrições")} </p>
                            </li>
                            <li>
                                <p className="num">
                                    {flatPoint(totalData?.recharge_user_count ?? 0)}
                                </p>
                                <p> {t("Jogadores")} </p>
                            </li>
                            <li>
                                <p className="num">
                                    <span className={"mr-[5px]"}>{t("R$")}</span>
                                    {flatPoint(totalData?.effective_amount ?? 0)}
                                </p>
                                <p> {t("ApostaTotal")} </p>
                            </li>
                            <li>
                                <p className="num">
                                    <span className={"mr-[5px]"}>{t("R$")}</span>
                                    {flatPoint(totalData?.commissar ?? 0)}
                                </p>
                                <p>RS {t("Comissão")} </p>
                            </li>
                        </ul>
                    </div>
                </div>
                <div className="content">
                    <div className="title">
                        <div>
                            {t("Comissão")}
                            <span
                                className="iconfont icon-bangzhu"
                                onClick={() => setVisible(true)}
                            />
                        </div>
                    </div>
                    <div className="cardMian">
                        <div className="vip">
                            <div className="level">
                                {/*<span className="iconfont icon-vip"></span>*/}
                                <Image
                                    src={"/summary/level.png"}
                                    alt={"level"}
                                    height={120}
                                    width={120}
                                />
                                <span className="levelNum">{commissionData?.level}</span>
                            </div>
                            <div>
                                {t("Nível")}
                                <span
                                    className="iconfont icon-tishi"
                                    onClick={() => setVisible(true)}
                                ></span>
                            </div>
                        </div>
                        <div>
                            <ul className="commission">
                                <li>
                                    <p className="num">
                                        <span>{t("R$")}</span>
                                        <span className="cash">
                                            {flatPoint(commissionData?.withdrawal_commissions ?? 0)}
                                        </span>
                                    </p>
                                    <p> {t("TotalPago")} </p>
                                </li>
                                <li>
                                    <p className="num">
                                        <span>{t("R$")}</span>
                                        <span className="cash">
                                            {flatPoint(commissionData?.commissar ?? 0)}
                                        </span>
                                    </p>
                                    <p> {t("Não")} </p>
                                </li>
                            </ul>
                            <div className="wallet">
                                <div className="btn" onClick={withdrawalHandler}>
                                    {t("TRANSFERIR")}
                                </div>
                                <div className="tip">
                                    <span className="iconfont icon-tishi1"></span>
                                    {t("Valor")}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div className="content shareMain">
                    <div className="title">
                        <div>{t("title1")}</div>
                    </div>

                    <div className="share">
                        <ul className="sharePlatform">
                            {SHARE_SOURCE.map((item, index) => {
                                return (
                                    <a
                                        href={item.shareUrl}
                                        key={index}
                                        target={"_blank"}
                                        className={"flex flex-col items-center"}
                                    >
                                        <Image
                                            src={item.icon}
                                            alt={"Mais"}
                                            width={70}
                                            height={70}
                                        />
                                        <p className={"mt-[0.0347rem] text-[12px] text-[#808080]"}>
                                            {item.label}
                                        </p>
                                    </a>
                                );
                            })}
                        </ul>
                    </div>

                    <div className="shareLink">
                        <div className="">{t("content1")}</div>
                        <div className="copyUrl">
                            <span className="url omitWrap">{shareUrl}</span>
                            <span id="copy" onClick={() => copy(shareUrl)}>
                                {t("Cópia")}
                            </span>
                        </div>
                    </div>
                </div>
                <div className="content">
                    <div className="title">
                        <div> {t("title2")}</div>
                    </div>
                    <div>
                        <div className="tel-box">
                            <a href="" className="telicon">
                                <Image
                                    src="/summary/telegram-nobg.png"
                                    height={100}
                                    width={100}
                                    alt="telegram"
                                />
                            </a>
                            <div className="hintTitle3">{t("content2-1")}</div>
                        </div>
                        <div className="hintTitle2">
                            <i className="iconfont icon-tishi"></i>
                            {t("content2-2")}
                            <a
                                href="https://t.me/jogobcwinOfficialChanel"
                                target={"_blank"}
                                style={{
                                    borderBottom: "1px solid rgb(109, 155, 195)",
                                    color: "#0000EE",
                                }}
                            >
                                {t("business")}
                            </a>
                        </div>
                    </div>
                </div>
                <div className="content">
                    <div className="title">
                        <div>
                            {t("title3")}
                            <span
                                className="iconfont icon-bangzhu"
                                onClick={() => setVisible(true)}
                            ></span>
                        </div>
                    </div>
                    <div className="hint">
                        <div className="hintTitle">{t("content3")}</div>
                        <div className="imgContent">
                            <Image width={100} height={100} src="/summary/money.png" alt="" />
                            <div>
                                {t("number")}
                                {num}
                                <br />
                                {t("Comissão")} &gt; {t("R$")} {money} {t("money")}
                            </div>
                            <div
                                className="slider van-slider"
                                style={{ height: "0.02rem" }}
                                onClick={handleSlide}
                            >
                                <div
                                    className="van-slider__bar"
                                    style={{ width: "0.900901%", background: "rgb(0, 157, 128)" }}
                                    ref={sliderRef}
                                >
                                    <div role="slider" className="van-slider__button-wrapper">
                                        <div className="img"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="relationSchema">
                            <div className="groupTitle">{t("title4")}</div>
                            <img src="/summary/group_br.png" alt="" className="groupImg" />
                            <ul className="rules">
                                <li>
                                    {t("content4-1")}
                                    <span style={{ color: "red" }}>{t("red")}</span>.
                                </li>
                                <li>{t("content4-2")}</li>
                            </ul>
                        </div>
                    </div>
                </div>
                <div className="content"></div>
            </div>

            <TipsModal title={t("modalTitle")} ref={todayModalRef}>
                <ul className={"list-decimal break-all p-[0.1389rem] pt-0 font-bold"}>
                    <li>{t("todayDesc1")}</li>
                    <li>{t("todayDesc2")}</li>
                    <li>{t("todayDesc3")}</li>
                </ul>
                <p className={"text-[gray]"}>{t("modalTips")}</p>
            </TipsModal>

            <TipsModal title={t("modalTitle")} ref={totalModalRef}>
                <ul className={"list-decimal break-all p-[0.1389rem] pt-0 font-bold"}>
                    <li>{t("totalDesc1")}</li>
                    <li>{t("totalDesc2")}</li>
                    <li>{t("totalDesc3")}</li>
                </ul>
                <p className={"text-[gray]"}>{t("modalTips")}</p>
            </TipsModal>

            <Mask visible={visible} getContainer={null}>
                <div className={"h-[100vh] w-[100%] overflow-scroll bg-[#1f2024]"}>
                    <div
                        className={
                            "absolute top-0 flex items-center justify-between " +
                            " h-[0.4167rem] w-[100%] border-[1px] bg-[#17181c] px-[0.1389rem]" +
                            " z-10 border-[#666]"
                        }
                    >
                        <p>Regras de recompensas por comissão</p>
                        <i className={"iconfont icon-guanbi"} onClick={() => setVisible(false)}></i>
                    </div>
                    <div className={"mt-[0.4167rem] px-[0.1389rem] pt-[0.1389rem]"}>
                        <RulesClient />
                    </div>
                </div>
            </Mask>
        </div>
    );
};

export default App;
